package com.example.myapplication8;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private MyDatabaseHelper dbHelper;
    private List<Book> bookList;

    private List<Book> getBooks(){
        bookList = new ArrayList<>();
        dbHelper = new MyDatabaseHelper(this,"BookLibrary.db",null,2);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("Book", null, null, null, null, null, null);
        if(cursor.moveToFirst()){
            do{
                Book book = new Book();
                @SuppressLint("Range") String bookName = cursor.getString(cursor.getColumnIndex("name"));
                @SuppressLint("Range") int bookPrice = cursor.getInt(cursor.getColumnIndex("price"));
                @SuppressLint("Range") int bookType = cursor.getInt(cursor.getColumnIndex("category_id"));
                book.setName(bookName);
                book.setPrice(bookPrice);
                book.setBooktype(bookType);
                bookList.add(book);
            }while (cursor.moveToNext());
        }
        cursor.close();

        return bookList;
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        List<Book> books = getBooks();
        BookAdapter adapter = new BookAdapter(MainActivity.this,R.layout.book_item,books);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);
        Button addButton = findViewById(R.id.add_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,AddBookActivity.class);
                startActivity(intent);
            }
        });


    }
}